<?php
		
	/**
	 * PHPLogger
	 */
		
	class PHPLogger  {

		protected $_path = '.';		
		protected $_fileName = 'phpLogger.log';
		protected $_LEVELS = array("FATAL"=>1,"ERROR"=>2,"WARNING"=>3, "INFO"=>4, "DEBUG"=>5,);
		protected $_level = 5;

		public function __construct($path, $level) {
			if (empty($path)){
				$path = '.';
			}
			if (!empty($level)){
				$this->_level = (int)$level;
				if ($this->_level<0) $this->_level = 0;
				if ($this->_level>5) $this->_level = 5;
			}			
			if (!file_exists($path)) {
				echo "PHPLogger :: The Path doesn't exists.";
				Throw new Exception("PHPLogger :: The Path doesn't exists.");
			}
			if (!is_writeable($path)) {
				echo "PHPLogger :: You can write on the give path";
				Throw new Exception("PHPLogger :: You can write on the give path");
			}
			$this->_path = $this->_parsePath($path);
		}	

		protected function _parsePath($path) {
			$strLenght = strlen($path);
        	$lastChar = substr($path, $strLenght - 1, $strLenght);
        	$path = $lastChar != "/" ? $path . "/" : $path;
        	if ( is_dir($path) ) {
        		return $path . $this->_fileName;
        	} else {
        		return $path;
        	}
		}

		protected function _save($line) {
			$size = 0;
			if(file_exists($this->_path)){
				$size = filesize($this->_path);
			}
			if($size >= SIZE_MAX_LOG){// mayor a 1Mb renombro el archivo y creo uno nuevo
				$vPathOld 	= explode($this->_fileName,$this->_path);
				$vNameOld 		= explode(".",$this->_fileName);
				$fileNameOld 	= $vNameOld[0].time().".".$vNameOld[1];
				$pathNew		= $vPathOld[0].$fileNameOld;	
				rename($this->_path,$pathNew);
			}
			$fhandle = fopen($this->_path, "a+");
			fwrite($fhandle, $line);
			fclose($fhandle);
		}
		
		public function getLevel() {
			return($this->_level);
		}
		
		public function getPath() {
			return($this->_path);
		}

		public function addLine($level, $line){
			$level = strtoupper($level);
			$levelValue = $this->_LEVELS[$level];
			if ((!empty($levelValue))&&((int)$levelValue <= $this->_level)){
				$line = date("d-m-Y h:i:s") . " [$level] " . ": $line\n";
				$this->_save($line);
			}
		}
	}

?>